﻿using System.Linq;
using Iesi.Collections.Generic;
using NHibernate;
using ReAnimation.DAL.RepositoryInterfaces;
using ReAnimation.Domain;
using ReAnimation.Legacy.DAL;

namespace ReAnimation.DAL.Repository
{
    public class AtomDescriptionRepository: IAtomDescriptionRepository
    {
        private INHibernateUtil _nhibernateUtil;
        private readonly ISet<AtomDescription> _atomsDescriptions;
        //TODO: not sure it is a right way
        public AtomDescriptionRepository(INHibernateUtil nhibernateUtil)
        {
            _nhibernateUtil = nhibernateUtil;
            ISession session = nhibernateUtil.OpenSession();

            _atomsDescriptions = new HashedSet<AtomDescription>(session.CreateCriteria<AtomDescription>().List<AtomDescription>());

            _nhibernateUtil.CloseSession();
        }

        public ISet<AtomDescription> GetAll()
        {
            return new HashedSet<AtomDescription>(_atomsDescriptions);
        }

        public AtomDescription GetByName(string name)
        {
            return (from atom in _atomsDescriptions where atom.Name == name select atom).Single();
        }

        public void UpdateAtomDescription(AtomDescription atomDescription)
        {
            ISession session = _nhibernateUtil.OpenSession();

            var atomDescFromDB= session.Get<AtomDescription>(atomDescription.Name);

            if(atomDescFromDB != null)
            {
                atomDescFromDB.Radius = atomDescription.Radius;
                atomDescFromDB.Color = atomDescription.Color;

                session.Update(atomDescFromDB);
                
                session.Flush();
            }

            _nhibernateUtil.CloseSession();

        }
    }
}
